package com.ccut.xunfeiSpringboot.utils;

import com.ccut.xunfeiSpringboot.common.JwtProperties;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtils {

    private static final long EXPIRATION = 86400000; // 24小时，单位毫秒

    private static Key SECRET_KEY;

    public JwtUtils(JwtProperties jwtProperties) {
        String key = jwtProperties.getSecretKey();
        if (key == null || key.isEmpty()) {
            SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512); // 自动生成安全密钥
        } else {
            SECRET_KEY = Keys.hmacShaKeyFor(jwtProperties.getSecretKey().getBytes()); // 手动设置
        }
    }

    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SECRET_KEY)
                .compact();
    }

    public Map<String, Object> parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
